﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using LucasCode.Tools;
using LucasCode.PublicTypes;
using System.Threading;
using System.IO;
using UserNotifier;
using ESLReminder.Games;
using GlobalSettings;
using Settings = GlobalSettings.Properties.Settings;

namespace ESLReminder.Modules
{
    public class AequitasModule : ReminderModule
    {
        public AequitasModule()
            : base( new PluginInfo( "AequitasReminder",
                                    new Version(1,0),
                                    "©2009 Lucas Romero",
                                    "http://code.google.com/p/quicktools/"),
                    Properties.Resources.AequitasModuleDescription)
        {
            
        }
        private Process m_Process = null;
        private Process m_GameProcess = null;
        FileSystemWatcher AequitasWatcher;
        public override void PluginLoadedEx(IReminderInterface host)
        {
            host.GameStarted += new GameStartedEventHandler(m_Reminder_GameStarted);
        }

        void m_Reminder_GameStarted(IReminderInterface sender, GameStartedEventArgs args)
        {
            Type g = args.Game.GetType();
            if (g != typeof(GameHalfLife) && g != typeof(GameHalfLife2))
                return;
            if (!ESLHelpers.isAequitasMonitoring())
            {
                Trace.TraceInformation(Properties.Resources.AequitasModuleNotMonitoring);
                m_Reminder.AddWarning(WarnEvents.NoAequitas, Timeout.Infinite);
            }
            else
            {
                Trace.TraceInformation(Properties.Resources.AequitasModuleMonitoring);
                GetAequitasMatchlink();
                //initialize aeqwatcher
                StartAequitasWatcher();
            }
            //initialize aeq-process
            m_Process = null;
            m_GameProcess = args.Game.Process;
            Process[] RunningProcesses = Process.GetProcessesByName("aequitas");
            if (RunningProcesses.Length > 0)
                m_Process = RunningProcesses[0];
        }
        void AequitasProcess_Exited(object sender, EventArgs e)
        {
            if (AequitasWatcher != null)
            {
                AequitasWatcher.EnableRaisingEvents = false;
                AequitasWatcher.Dispose();
                AequitasWatcher = null;
            }
            // warn if aequitas dies before the game does
            if (m_GameProcess != null && !m_GameProcess.HasExited)
            {
                m_Reminder.AddWarning(WarnEvents.NoAequitas, Timeout.Infinite);
            }
        }
        void AequitasWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            if (!m_Reminder.CurrentArchive.containsFile(e.FullPath))
                m_Reminder.CurrentArchive.AddFile(new MatchFile(e.FullPath));
        }
        private void StartAequitasWatcher()
        {
            if (m_Process != null)
            {
                LogInfo("Setting up aequitaswatcher");
                m_Process.Exited += new EventHandler(AequitasProcess_Exited);
                m_Process.EnableRaisingEvents = true;
                try
                {
                    AequitasWatcher = null;
                    AequitasWatcher = new FileSystemWatcher(Path.GetDirectoryName(m_Process.MainModule.FileName) + Path.DirectorySeparatorChar + "archive", "*.ZIP");
                    AequitasWatcher.IncludeSubdirectories = true;
                    AequitasWatcher.InternalBufferSize = 4 * AequitasWatcher.InternalBufferSize;
                    AequitasWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size;
                    AequitasWatcher.Created += new FileSystemEventHandler(AequitasWatcher_Changed);
                    AequitasWatcher.Changed += new FileSystemEventHandler(AequitasWatcher_Changed);
                    AequitasWatcher.EnableRaisingEvents = true;
                }
                catch { }
                LogInfo("Aequitas watcher setup " + AequitasWatcher != null ? "successful." : "failed!");
            }
        }
        private void GetAequitasMatchlink()
        {
            m_Reminder.CurrentArchive.Matchlink = ESLHelpers.getMatchLink();

            if (m_Reminder.CurrentArchive.Matchlink != string.Empty && Settings.Default.Cookie != string.Empty)
            {
                try
                {
                    WebSynchronizer.UpdateDetailsFromWeb(Settings.Default.Cookie, MatchInfoFlags.AequitasInfo | MatchInfoFlags.MapInfo | MatchInfoFlags.PlayerInfo | MatchInfoFlags.ScoreInfo | MatchInfoFlags.TeamInfo, m_Reminder.CurrentArchive);
                }
                catch (Exception ex)
                {
                    LogError("Error Parsing website: " + ex);
                }
            }
        }
    }
}
